import { ZYSDK } from "../../../ZYSDK";
import adModel from "../../main/view/adView/adModel";
import gameModel from "../model/gameModel";
import { ZYNetMgr } from "../server/ZYNetMgr";
import ArrayUtils from "../util/ArrayUtils";
import AsyncUtils from "../util/AsyncUtils";
import { WXAPIMgr } from "../wxComponent/concrete/WXAPIManager";
import AbstractBean from "./AbstractBean";

/**
 * 
 * @author: xj.huang
 * @date: 2021/07/31 18:45:06
 */
export default class loginBean extends AbstractBean {
    private SDK_VERSION = '20200430v1.2.2';
    constructor() {
        super("InitGameBean")
    }
    async start() {
        this.login().then(this.onLoginResult.bind(this));
        this.finish()
    }
    private async onLoginResult(loginResult) {
        if (!loginResult) return console.log("登录失败！");
        let initSessionInfo = adModel.initSessionInfo;
        initSessionInfo.s_update_time = new Date().getTime();
        for (var k in initSessionInfo) {
            if (loginResult[k]) initSessionInfo[k] = loginResult[k]
        }
        this.onInitUserInfo(loginResult)
        let result = await ZYNetMgr.getConfig() as any;
        this.onPostUserDua(loginResult)
        if (result.code == 200) this.assignObj(result.data)
        WXAPIMgr.setStorage(session.SESSION_INFO, adModel.initSessionInfo)
        // console.log("登录成功，头像：", adModel.initSessionInfo);
    }
    /**初始化游戏数据 */
    private onInitUserInfo(data) {
        gameModel.loginData = ArrayUtils.conleData(data) || {};
        if (gameModel.loginData.user?.ext_data) {
            gameModel.userData = JSON.parse(gameModel.loginData.user.ext_data);
            gameModel.currLevel = gameModel.userData.currLevel;
        } else {
            gameModel.loginData.user.ext_data = gameModel.userData;
            ZYNetMgr.updateUserExtData(
                {
                    ext_data: JSON.stringify(gameModel.userData),
                    province: gameModel.loginData.user.ip_province,
                    city: gameModel.loginData.user.ip_ip_city
                }
            );
        }
    }
    /**上报用户数据 */
    private async onPostUserDua(loginResult) {
        let param = ArrayUtils.conleData(this.stratConfig.config)
        param.is_new = loginResult.is_new;
        param.reg_time = loginResult.reg_time;
        param.openid = loginResult.openid;
        param.sdk_version = this.SDK_VERSION + '-' + this.stratConfig.config.version
        param.version = this.stratConfig.config.wx_version;
        let result = await ZYNetMgr.updataUseInfo(param) as any;
        if (result.code == 200) {
            console.warn("数据更新成功")
        }
    }

    /**合并数据 */
    private assignObj(targetObj) {
        let newResult = ArrayUtils.conleData(targetObj)
        Object.assign(ZYSDK.gameConfig, newResult)
    }
    /**登录 */
    private async login() {
        const MAX = 3;//请求后台登录的最大次数
        let retryTime = 0;//当前请求次数
        let code = "";
        let rsp;
        // let options = window['wx'] && window['wx']['getLaunchOptionsSync']() || {};
        /** 请求平台登录 */
        const doPlatfromLogin = async () => {
            try {
                const result = await WXAPIMgr.login();
                code = result.code;
                console.log(`【登录】app登录成功：${code}`);
            } catch (error) {
                code = "";
                return error;
            }
            return "";
        };
        /** 请求后端登录 */
        const doBackendLogin = async () => {
            const data = WXAPIMgr.launchOptions;
            const param = this.stratConfig.config;

            
            this.stratConfig.config.app_id = data.referrerInfo.appId;
            this.stratConfig.config.share_id = parseInt(data.query.share_id) || 0;
            this.stratConfig.config.scene_id = data.scene;


            param.code = code;
            param.application_id = ZYSDK.config.server.APPID;
            param.channel_id = data.query.channel_id || '';
            param.share_id = parseInt(data.query.share_id) || 0;
            param.scene_id = data.scene;
            param.app_id = data.referrerInfo.appId
            param.wx_version = window['wx'].getSystemInfoSync().version;
            param.version = ZYSDK.config.server.apiversion//.data.CUR_VERSION;
            rsp = await ZYNetMgr.login(param);
        };
        while (true) {
            const errorMsg = await doPlatfromLogin();
            if (!code) {
                console.log(`【登录】app登录失败：${errorMsg}，${code}`);
            } else {
                await doBackendLogin();
                if (rsp.code == 200) {
                    return rsp.data;//请求成功

                }
                console.log(`【登录】后台失败，错误代码：${rsp.code}，原因：${rsp.msg}`);
            }
            //请求失败，重新请求
            retryTime++;
            if (retryTime < MAX) {
                await AsyncUtils.sleep(1000);//1秒钟后重试
                //一旦登录出错，必须重新进行app登录，获取最新的code或者token，像wx那样，一个code不允许重复使用
            } else {
                this.stratConfig.innerConf.retry_count;
                console.log(`登录失败，已经超过最大重试次数（${MAX}次）。`);
                return;
            }
        }
    }
    /**定义接口 */
    private get stratConfig() {
        return this._stratConfig
    }
    private _stratConfig = {
        innerConf: {
            no_action: 0,
            no_export: 0,
            no_share: 0,
            no_dau: 0,
            no_adv: 0,
            no_form_id: 0,
            no_subscribe_msg: 0,
            retry_count: 1, // 重试次数,
            user_ext_data_push_interval: 3 // 用户数据上报周期
        },
        config: {
            app_id: "",
            application_id: null,
            channel_id: '',
            code: '',
            scene_id: 0,
            inviter_code: '',
            scene: '',
            share_id: 0,
            version: null,
            wx_version: '',
        }
    }
}